//
//  FetchFileDataView.swift
//  sui04mac
//
//  Created by 杨剑 on 2024/4/12.
//

import SwiftUI

struct FetchFileDataView: View {
    @State var fileData: Data?
    @State var filePath: String = "" // 这里输入你的文件路径

    var body: some View {
        VStack {
            TextField("请输入文件路径", text: $filePath)
                .textFieldStyle(RoundedBorderTextFieldStyle())
            Button("加载文件数据") {
//                作者：知乎用户
//                链接：https://www.zhihu.com/question/616572563/answer/3159012296
//                来源：知乎
//                著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。

                let dialog = NSOpenPanel();
                dialog.title                   = "Choose a file";
                dialog.showsResizeIndicator    = true;
                dialog.showsHiddenFiles        = false;
                dialog.canChooseDirectories    = true;
                dialog.canCreateDirectories    = true;
                dialog.allowsMultipleSelection = false;

                if (dialog.runModal() == NSApplication.ModalResponse.OK) {
                    let result = dialog.url
                    if (result != nil) {
                        let path = result!.path
                        print(path)
                        
                        let url = URL(fileURLWithPath: path)
                        fileData = FileManager.default.contents(atPath: url.path)

                    }
                } else {
                    return
                }
            }
            if fileData != nil {
                Text("文件数据已加载")
            } else {
                Text("文件数据未加载")
            }
        }
    }
    func loadFileData() {
        let path = filePath
        let url = URL(fileURLWithPath: path)
//        guard url else {
//            print("无效的文件路径")
//            return
//        }///Users/yj/Downloads
        fileData = FileManager.default.contents(atPath: url.path)
//        do {
//        } catch {
//            print("加载文件数据时发生错误: \(error.localizedDescription)")
//            fileData = nil
//        }
    }
}

#Preview {
    FetchFileDataView()
}
